{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "initial_id",
   "metadata": {
    "collapsed": true,
    "ExecuteTime": {
     "end_time": "2025-06-06T07:49:33.788707100Z",
     "start_time": "2025-06-06T07:49:33.467168700Z"
    }
   },
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "import numpy as np\n",
    "import os\n",
    "\n",
    "os.chdir(r'E:\\temp_dir\\workspace\\eee\\company_talent_loss\\wanghongge')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<class 'pandas.core.frame.DataFrame'>\n",
      "RangeIndex: 350 entries, 0 to 349\n",
      "Data columns (total 31 columns):\n",
      " #   Column                    Non-Null Count  Dtype \n",
      "---  ------                    --------------  ----- \n",
      " 0   Age                       350 non-null    int64 \n",
      " 1   BusinessTravel            350 non-null    object\n",
      " 2   Department                350 non-null    object\n",
      " 3   DistanceFromHome          350 non-null    int64 \n",
      " 4   Education                 350 non-null    int64 \n",
      " 5   EducationField            350 non-null    object\n",
      " 6   EmployeeNumber            350 non-null    int64 \n",
      " 7   EnvironmentSatisfaction   350 non-null    int64 \n",
      " 8   Gender                    350 non-null    object\n",
      " 9   JobInvolvement            350 non-null    int64 \n",
      " 10  JobLevel                  350 non-null    int64 \n",
      " 11  JobRole                   350 non-null    object\n",
      " 12  JobSatisfaction           350 non-null    int64 \n",
      " 13  MaritalStatus             350 non-null    object\n",
      " 14  MonthlyIncome             350 non-null    int64 \n",
      " 15  NumCompaniesWorked        350 non-null    int64 \n",
      " 16  Over18                    350 non-null    object\n",
      " 17  OverTime                  350 non-null    object\n",
      " 18  PercentSalaryHike         350 non-null    int64 \n",
      " 19  PerformanceRating         350 non-null    int64 \n",
      " 20  RelationshipSatisfaction  350 non-null    int64 \n",
      " 21  StandardHours             350 non-null    int64 \n",
      " 22  StockOptionLevel          350 non-null    int64 \n",
      " 23  TotalWorkingYears         350 non-null    int64 \n",
      " 24  TrainingTimesLastYear     350 non-null    int64 \n",
      " 25  WorkLifeBalance           350 non-null    int64 \n",
      " 26  YearsAtCompany            350 non-null    int64 \n",
      " 27  YearsInCurrentRole        350 non-null    int64 \n",
      " 28  YearsSinceLastPromotion   350 non-null    int64 \n",
      " 29  YearsWithCurrManager      350 non-null    int64 \n",
      " 30  Attrition                 350 non-null    int64 \n",
      "dtypes: int64(23), object(8)\n",
      "memory usage: 84.9+ KB\n",
      "None\n"
     ]
    }
   ],
   "source": [
    "test_source = pd.read_csv('./data/test2.csv')\n",
    "print(test_source.info())"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "end_time": "2025-06-06T07:50:48.004470400Z",
     "start_time": "2025-06-06T07:50:47.986018400Z"
    }
   },
   "id": "d03887ad474255da"
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<class 'pandas.core.frame.DataFrame'>\n",
      "RangeIndex: 350 entries, 0 to 349\n",
      "Data columns (total 23 columns):\n",
      " #   Column                    Non-Null Count  Dtype \n",
      "---  ------                    --------------  ----- \n",
      " 0   Age                       350 non-null    int64 \n",
      " 1   Department                350 non-null    int64 \n",
      " 2   DistanceFromHome          350 non-null    int64 \n",
      " 3   Education                 350 non-null    int64 \n",
      " 4   EnvironmentSatisfaction   350 non-null    int64 \n",
      " 5   Gender                    350 non-null    object\n",
      " 6   JobLevel                  350 non-null    int64 \n",
      " 7   JobSatisfaction           350 non-null    int64 \n",
      " 8   MaritalStatus             350 non-null    int64 \n",
      " 9   MonthlyIncome             350 non-null    int64 \n",
      " 10  NumCompaniesWorked        350 non-null    int64 \n",
      " 11  OverTime                  350 non-null    object\n",
      " 12  PercentSalaryHike         350 non-null    int64 \n",
      " 13  PerformanceRating         350 non-null    int64 \n",
      " 14  RelationshipSatisfaction  350 non-null    int64 \n",
      " 15  StockOptionLevel          350 non-null    int64 \n",
      " 16  TotalWorkingYears         350 non-null    int64 \n",
      " 17  WorkLifeBalance           350 non-null    int64 \n",
      " 18  YearsAtCompany            350 non-null    int64 \n",
      " 19  YearsInCurrentRole        350 non-null    int64 \n",
      " 20  YearsSinceLastPromotion   350 non-null    int64 \n",
      " 21  YearsWithCurrManager      350 non-null    int64 \n",
      " 22  Attrition                 350 non-null    int64 \n",
      "dtypes: int64(21), object(2)\n",
      "memory usage: 63.0+ KB\n",
      "None\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "C:\\Users\\Administrator\\AppData\\Local\\Temp\\ipykernel_6036\\3083642101.py:4: SettingWithCopyWarning: \n",
      "A value is trying to be set on a copy of a slice from a DataFrame.\n",
      "Try using .loc[row_indexer,col_indexer] = value instead\n",
      "\n",
      "See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n",
      "  df['MaritalStatus'] = df['MaritalStatus'].apply(lambda  x: 0 if x in ['Divorced','Single'] else 1)\n",
      "C:\\Users\\Administrator\\AppData\\Local\\Temp\\ipykernel_6036\\3083642101.py:5: SettingWithCopyWarning: \n",
      "A value is trying to be set on a copy of a slice from a DataFrame.\n",
      "Try using .loc[row_indexer,col_indexer] = value instead\n",
      "\n",
      "See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n",
      "  df['Department'] = df['Department'].apply(lambda  x:0 if x in ['Sales','Human Resources'] else 1)\n"
     ]
    }
   ],
   "source": [
    "df = test_source[\n",
    "    ['Age', 'Department', 'DistanceFromHome', 'Education', 'EnvironmentSatisfaction', 'Gender', 'JobLevel', 'JobSatisfaction', 'MaritalStatus', 'MonthlyIncome', 'NumCompaniesWorked', 'OverTime', 'PercentSalaryHike', 'PerformanceRating', 'RelationshipSatisfaction', 'StockOptionLevel', 'TotalWorkingYears', 'WorkLifeBalance', 'YearsAtCompany', 'YearsInCurrentRole', 'YearsSinceLastPromotion', 'YearsWithCurrManager','Attrition']]\n",
    "\n",
    "df['MaritalStatus'] = df['MaritalStatus'].apply(lambda  x: 0 if x in ['Divorced','Single'] else 1)\n",
    "df['Department'] = df['Department'].apply(lambda  x:0 if x in ['Sales','Human Resources'] else 1)\n",
    "# print(df.info())"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "end_time": "2025-06-06T07:54:25.383599100Z",
     "start_time": "2025-06-06T07:54:25.374975800Z"
    }
   },
   "id": "cd344c9cf933cfdf"
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<class 'pandas.core.frame.DataFrame'>\n",
      "RangeIndex: 350 entries, 0 to 349\n",
      "Data columns (total 25 columns):\n",
      " #   Column                    Non-Null Count  Dtype\n",
      "---  ------                    --------------  -----\n",
      " 0   Age                       350 non-null    int64\n",
      " 1   Department                350 non-null    int64\n",
      " 2   DistanceFromHome          350 non-null    int64\n",
      " 3   Education                 350 non-null    int64\n",
      " 4   EnvironmentSatisfaction   350 non-null    int64\n",
      " 5   JobLevel                  350 non-null    int64\n",
      " 6   JobSatisfaction           350 non-null    int64\n",
      " 7   MaritalStatus             350 non-null    int64\n",
      " 8   MonthlyIncome             350 non-null    int64\n",
      " 9   NumCompaniesWorked        350 non-null    int64\n",
      " 10  PercentSalaryHike         350 non-null    int64\n",
      " 11  PerformanceRating         350 non-null    int64\n",
      " 12  RelationshipSatisfaction  350 non-null    int64\n",
      " 13  StockOptionLevel          350 non-null    int64\n",
      " 14  TotalWorkingYears         350 non-null    int64\n",
      " 15  WorkLifeBalance           350 non-null    int64\n",
      " 16  YearsAtCompany            350 non-null    int64\n",
      " 17  YearsInCurrentRole        350 non-null    int64\n",
      " 18  YearsSinceLastPromotion   350 non-null    int64\n",
      " 19  YearsWithCurrManager      350 non-null    int64\n",
      " 20  Attrition                 350 non-null    int64\n",
      " 21  Gender_Female             350 non-null    bool \n",
      " 22  Gender_Male               350 non-null    bool \n",
      " 23  OverTime_No               350 non-null    bool \n",
      " 24  OverTime_Yes              350 non-null    bool \n",
      "dtypes: bool(4), int64(21)\n",
      "memory usage: 58.9 KB\n",
      "None\n"
     ]
    }
   ],
   "source": [
    "df2 = pd.get_dummies(df)\n",
    "print(df2.info())"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "end_time": "2025-06-06T07:57:02.087301700Z",
     "start_time": "2025-06-06T07:57:02.072746400Z"
    }
   },
   "id": "6a902e224fde2248"
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<class 'pandas.core.frame.DataFrame'>\n",
      "RangeIndex: 350 entries, 0 to 349\n",
      "Data columns (total 23 columns):\n",
      " #   Column                    Non-Null Count  Dtype\n",
      "---  ------                    --------------  -----\n",
      " 0   Age                       350 non-null    int64\n",
      " 1   Department                350 non-null    int64\n",
      " 2   DistanceFromHome          350 non-null    int64\n",
      " 3   Education                 350 non-null    int64\n",
      " 4   EnvironmentSatisfaction   350 non-null    int64\n",
      " 5   JobLevel                  350 non-null    int64\n",
      " 6   JobSatisfaction           350 non-null    int64\n",
      " 7   MaritalStatus             350 non-null    int64\n",
      " 8   MonthlyIncome             350 non-null    int64\n",
      " 9   NumCompaniesWorked        350 non-null    int64\n",
      " 10  PercentSalaryHike         350 non-null    int64\n",
      " 11  PerformanceRating         350 non-null    int64\n",
      " 12  RelationshipSatisfaction  350 non-null    int64\n",
      " 13  StockOptionLevel          350 non-null    int64\n",
      " 14  TotalWorkingYears         350 non-null    int64\n",
      " 15  WorkLifeBalance           350 non-null    int64\n",
      " 16  YearsAtCompany            350 non-null    int64\n",
      " 17  YearsInCurrentRole        350 non-null    int64\n",
      " 18  YearsSinceLastPromotion   350 non-null    int64\n",
      " 19  YearsWithCurrManager      350 non-null    int64\n",
      " 20  Attrition                 350 non-null    int64\n",
      " 21  Gender_Female             350 non-null    bool \n",
      " 22  OverTime_Yes              350 non-null    bool \n",
      "dtypes: bool(2), int64(21)\n",
      "memory usage: 58.2 KB\n",
      "None\n"
     ]
    }
   ],
   "source": [
    "#去掉重复的object对象\n",
    "df3 = df2.drop(['Gender_Male', 'OverTime_No'], axis=1)\n",
    "print(df3.info())"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "end_time": "2025-06-06T07:57:19.601429900Z",
     "start_time": "2025-06-06T07:57:19.593515400Z"
    }
   },
   "id": "e4750522afca5a51"
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "outputs": [],
   "source": [
    "#从预处理后的数据列中找出特征列和标签\n",
    "x = df3[['Age','EnvironmentSatisfaction','JobSatisfaction','MaritalStatus','MonthlyIncome','NumCompaniesWorked','PercentSalaryHike','PerformanceRating','RelationshipSatisfaction','StockOptionLevel','TotalWorkingYears','WorkLifeBalance','YearsAtCompany','YearsInCurrentRole','YearsSinceLastPromotion','Gender_Female','OverTime_Yes']]\n",
    "y= df3['Attrition']\n"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "end_time": "2025-06-06T08:12:29.154860300Z",
     "start_time": "2025-06-06T08:12:29.147093Z"
    }
   },
   "id": "76967305fbfffee5"
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "outputs": [],
   "source": [
    "from sklearn.preprocessing import StandardScaler    \n",
    "from sklearn.preprocessing import LabelEncoder\n",
    "import joblib\n",
    "from sklearn.metrics import accuracy_score, roc_auc_score\n",
    "import matplotlib\n",
    "matplotlib.use('TkAgg')\n",
    "import matplotlib.pyplot as plt"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "end_time": "2025-06-06T08:17:49.599236900Z",
     "start_time": "2025-06-06T08:17:49.124604800Z"
    }
   },
   "id": "f4e4fd0ba51ae42a"
  },
  {
   "cell_type": "code",
   "execution_count": 32,
   "outputs": [],
   "source": [
    "#对标签进行编码处理\n",
    "le = LabelEncoder()\n",
    "y = le.fit_transform(y)\n",
    "#对特征进行标准化处理\n",
    "transfer = StandardScaler()\n",
    "x = transfer.fit_transform(x)"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "end_time": "2025-06-06T08:39:38.578909200Z",
     "start_time": "2025-06-06T08:39:38.571731700Z"
    }
   },
   "id": "b7ca0417e151e08c"
  },
  {
   "cell_type": "code",
   "execution_count": 34,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "测试集的准确率：0.8085714285714286\n",
      "测试集的AUC值0.6159392668826631\n"
     ]
    }
   ],
   "source": [
    "#加载本地的模型\n",
    "dtcModel = joblib.load('./model/2025060612_dtcModel.pkl')\n",
    "# dtcModel = joblib.load('./model/2025060612_xgbModel.pkl')\n",
    "y_pred = dtcModel.predict(x)\n",
    "# print(y_pred.to_string())\n",
    "print(f\"测试集的准确率：{accuracy_score(y,y_pred)}\")\n",
    "print(f\"测试集的AUC值{roc_auc_score(y,y_pred)}\")"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "end_time": "2025-06-06T08:39:46.458502900Z",
     "start_time": "2025-06-06T08:39:46.450520400Z"
    }
   },
   "id": "1991035d52b244ff"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "outputs": [],
   "source": [],
   "metadata": {
    "collapsed": false
   },
   "id": "ef2380a2f7a8dd50"
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
